package com.timothy.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

public class BackLightService extends Service {
	private static final String LOG_TAG = "BackLightService";
	
	public static final int MSG_DARK = 1;
	public static final int MSG_REGISTER_CLIENT = 1;
	public static final int MSG_UNREGISTER_CLIENT = 2;
	public static final int MSG_TOUCH_SCREEN = 3;
	
	final Messenger rMessenger = new Messenger(new IncomingHandler());
	Map<Messenger, Long> sMessengerAndLastTouchTime = new HashMap<Messenger, Long>();
	
	public static final float TIME_CHANGE_DARK = 30000;// ms
	
	@Override
	public IBinder onBind(Intent intent) {
		return rMessenger.getBinder();
	}

	@Override
	public void onCreate() {
		Thread timeThread = new TimeThread();
		timeThread.start();
	}

	public class TimeThread extends Thread {
		public void run() {
			List<Messenger> needRemove = new ArrayList<Messenger>();
			while (true) { 
				try {
					sleep( 1000 );
				} catch (InterruptedException e1) {}
				
				long currentTime = Calendar.getInstance().getTimeInMillis();
				
				for( Map.Entry<Messenger, Long> en : sMessengerAndLastTouchTime.entrySet() ) {

					Log.i(LOG_TAG,"currentTime:"+currentTime);
					Log.i(LOG_TAG,"screenLastTouchTime:"+en.getValue());
					Log.i(LOG_TAG,"time screen not touched:"+ (currentTime - en.getValue()));
					
					//screen is not touched in 10 seconds
			        if( (currentTime - en.getValue()) > TIME_CHANGE_DARK ) {
			        	Message msg = Message.obtain(null, MSG_DARK);
			        	try {
			        		en.getKey().send( msg );
			        	} catch (RemoteException e) {
			        		needRemove.add( en.getKey() );
			        	}
			            
			        }
				}
				
				if( !needRemove.isEmpty() ) {
					for( Messenger key : needRemove) {
						sMessengerAndLastTouchTime.remove(key);
					}
					needRemove.clear();
				}
			}
		}
	}
	
	class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_REGISTER_CLIENT:
                	sMessengerAndLastTouchTime.put(msg.replyTo, System.currentTimeMillis());
                    break;
                case MSG_UNREGISTER_CLIENT:
                	sMessengerAndLastTouchTime.remove(msg.replyTo);
                    break;
                case MSG_TOUCH_SCREEN:
                	sMessengerAndLastTouchTime.put(msg.replyTo, System.currentTimeMillis());
                	break;
            }
        }
    }
}
